﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Super64.Core;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using Super64.Core.Memory.Rom;

namespace Super64
{
    public static class N64Manager
    {
        private static GameListManager s_GameManager;
        private static N64Machine m_VM;
        private static bool m_Init = false;

        static N64Manager()
        {
            s_GameManager = new GameListManager();
        }

        public static void InitMachine()
        {
            m_VM = new N64Machine();
            m_Init = true;
        }

        public static GameListManager GameList
        {
            get { return s_GameManager; }
        }

        public static N64Machine N64VirtualMachine
        {
            get { return m_VM; }
        }

        public static void OpenRom(GameListEntry entry)
        {
            if (!m_Init)
                throw new InvalidOperationException("VM has not been initialized yet!");

            // Open a file stream for the rom file
            FileStream file = new FileStream(entry.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            
            Stream source = file;

            switch (Path.GetExtension(entry.FilePath).ToLower())
            {
                case ".zip": source = ArchiveTools.DecompressZipEntry(entry); break;
                case ".bz2": source = ArchiveTools.DecompressBzip2(entry); break;
                case ".7z": source = ArchiveTools.Decompress7ZipEntry(entry); break;
                default: break;
            }

            // Set the resource rom stream
            ((N64Resources)N64Manager.N64VirtualMachine.Resources).LoadRom(new CartRom(source));
        }
    }
}
